<template>
  <div>
    <ElConfigProvider :locale="zhCn">
      <Drawer v-if="visible && position == 'drawer'" v-bind="getBindValue" @close="close">
        <template v-if="slots.title" #title>
          <slot name="title" :close="close"></slot>
        </template>
        <slot :close="close"></slot>
        <template v-if="slots.footer" #footer>
          <slot name="footer" :close="close"></slot>
        </template>
      </Drawer>
      <Dialog v-if="visible && position == 'dialog'" v-bind="getBindValue" @close="close">
        <template v-if="slots.title" #title>
          <slot name="title" :close="close"></slot>
        </template>
        <slot :close="close"></slot>
        <template v-if="slots.footer" #footer>
          <slot name="footer" :close="close"></slot>
        </template>
      </Dialog>
      <Card v-else-if="visible" v-bind="getBindValue" @close="close">
        <template v-if="slots.title" #title>
          <slot name="title" :close="close"></slot>
        </template>
        <slot :close="close"></slot>
        <template v-if="slots.footer" #footer>
          <slot name="footer" :close="close"></slot>
        </template>
      </Card>
    </ElConfigProvider>
  </div>
</template>
<script setup lang="ts">
  import Dialog from './Dialog.vue'
  import Drawer from './Drawer.vue'
  import Card from './Card.vue'
  import { computed, provide, ref, useAttrs, useSlots } from 'vue'
  import { closePopupKey } from '..'
  import { Unit } from '@/seed-application/types'
  import { unitKey } from '@/seed-application'
  import { ElConfigProvider } from 'element-plus'  
  import zhCn from 'element-plus/es/locale/lang/zh-cn'

  const slots = useSlots()
  const props = defineProps<{
    title?: string,
    fullscreen?: boolean,
    position?: 'dialog' | 'drawer' | 'card',
    direction?: 'rtl' | 'ltr' | 'ttb' | 'btt',
    visible?: boolean,
    unit?: Unit
  }>()

  const emit = defineEmits(['close'])
  provide(closePopupKey, close)
  provide(unitKey, props.unit)

  const getBindValue = computed(() => {
    const delArr: string[] = ['position', 'visible']
    const attrs = useAttrs()
    const obj = { ...attrs, ...props, modelValue: props.visible }
    for (const key in obj) {
      if (delArr.indexOf(key) !== -1) {
        delete obj[key]
      }
    }
    if(props.position === 'drawer') delete obj.fullscreen
    if(props.position === 'dialog') delete obj.direction
    
    return obj
  })

  const visible = ref(props.visible)

  function close() {
    visible.value = false
    emit('close')
  }

  defineExpose({ close })
</script>